package cn.mihoyo.org.controller;


import cn.mihoyo.base.annotation.PreAuthorize;
import cn.mihoyo.base.util.AjaxResult;
import cn.mihoyo.base.util.PageList;
import cn.mihoyo.org.domain.Department;
import cn.mihoyo.org.query.DepartmentQuery;
import cn.mihoyo.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    @PostMapping
//    @PreAuthorize(name = "分页查询", sn="department:list")
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryByPage(departmentQuery);
    }

    @GetMapping("/{id}")
//    @PreAuthorize(name="根据ID查询", sn="department:get")
    public Department findById(@PathVariable("id")Long id){
        return departmentService.findById(id);
    }


    @DeleteMapping("/{id}")
    @PreAuthorize(name="部门删除", sn="department:delete")
    public AjaxResult delete(@PathVariable("id") Long id){
            departmentService.delete(id);
            return AjaxResult.me();

    }
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId() == null){
                departmentService.add(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        }catch (Exception e){
            return AjaxResult.fail();
        }
    }

    @PatchMapping
    public AjaxResult batchDepartment(@RequestBody List<Long> ids){
        try{
            departmentService.batchDel(ids);
            return AjaxResult.me();
        }catch (Exception e){
            return AjaxResult.fail();
        }
    }


    @GetMapping("/tree")
    public List<Department> tree(){
        return departmentService.findTree();
    }

}
